package com.scau.database.utils;

import com.scau.database.utils.entity.PathDO;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * word文件模板渲染工具类
 *
 *
 */
@Component
public class WordBuidUtil {
    @Autowired
    private PathDO pathDO;
    public void renderingWordModel2HTTP(HttpServletResponse httpServletResponse, String templateName, Map dataMap,String fileName0) throws IOException, TemplateException {

        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");

        String path = pathDO.getPath();
        configuration.setDirectoryForTemplateLoading(new File(path));
//        File outFile = new File("D:/进货单导出.doc");

        Template template = configuration.getTemplate(templateName,"utf-8");
//        Writer out = new BufferedWriter(new OutputStreamWriter(httpServletResponse.getOutputStream()));
////        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"),10240);
//        template.process(dataMap,out);
//        out.close();
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;

        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(dataMap,template);
            fin = new FileInputStream(file);
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            String fileName = fileName0 + ".doc";
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));

            out = httpServletResponse.getOutputStream();
            byte[] buffer = new byte[512];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if(fin != null) fin.close();
            if(out != null) out.close();
            if(file != null) file.delete(); // 删除临时文件
        }



    }
    private File createDoc(Map<?,?> dataMap ,Template template){
        String name = "temp" + (int) (Math.random() * 100000) + ".doc";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }

    @Async
    public void test(HttpServletResponse response) throws IOException {
        Writer out= new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                .concat(String.valueOf(URLEncoder.encode("fileName", "UTF-8"))));
        out.write("this is a message from async task ");
        out.flush();
    }
}
